package cn.lblbc.downloadlib;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 下载任务构建器
 */
public class DownloadTaskBuilder {
    private static final AtomicLong sFileIdGenerator = new AtomicLong(System.currentTimeMillis());
    
    private String packageName;
    private boolean onlyWifi = false;
    private List<DownloadFileInfo> files = new ArrayList<>();
    private String extraInfo;

    public DownloadTaskBuilder(String packageName) {
        this.packageName = packageName;
    }

    public DownloadTaskBuilder setOnlyWifi(boolean onlyWifi) {
        this.onlyWifi = onlyWifi;
        return this;
    }

    public DownloadTaskBuilder setFiles(List<DownloadFileInfo> files) {
        this.files = files != null ? files : new ArrayList<>();
        // 确保每个文件都有必要的信息
        for (DownloadFileInfo file : this.files) {
            if (file.getFileId() <= 0) {
                file.setFileId(sFileIdGenerator.getAndIncrement());
            }
            if (file.getCreateTime() <= 0) {
                file.setCreateTime(System.currentTimeMillis());
            }
            if (file.getUpdateTime() <= 0) {
                file.setUpdateTime(System.currentTimeMillis());
            }
            if (file.getStatus() < 0) {
                file.setStatus(DownloadConstants.STATUS_PENDING);
            }
        }
        return this;
    }

    public DownloadTaskBuilder setExtraInfo(String extraInfo) {
        this.extraInfo = extraInfo;
        return this;
    }

    public DownloadTask build() {
        DownloadTask task = new DownloadTask();
        task.setPackageName(packageName);
        task.setWifiOnly(onlyWifi);
        task.setFiles(files);
        task.setExtraInfo(extraInfo);
        task.setStatus(DownloadConstants.STATUS_PENDING);
        task.setCreateTime(System.currentTimeMillis());
        task.setUpdateTime(System.currentTimeMillis());
        
        // 计算总大小
        long totalSize = 0;
        for (DownloadFileInfo file : files) {
            totalSize += file.getFileSize();
        }
        task.setTotalSize(totalSize);
        task.setDownloadedSize(0);
        
        return task;
    }
}